package com.xxd.algo.newcode.mid01.class03;

public class Code02_RotateMatrix {

    public static void rotate(int[][] matrix) {
        // 开头左上角的位置
        int a = 0;
        int b = 0;

        // 右下角的位置
        int c = matrix.length - 1;
        int d = matrix[0].length - 1;

        while (a < c) {
            rotateEdge(matrix, a++, b++, c--, d--);
        }
    }

    /**
     * 边框内交换
     *
     * @param m 数组
     * @param a 左上角行号
     * @param b 左上角列号
     * @param c 右下角行号
     * @param d 右下角列号
     */
    public static void rotateEdge(int[][] m, int a, int b, int c, int d) {
        int tmp = 0;
        for (int i = 0; i < d - b; i++) {
            tmp = m[a][b + i];
            m[a][b + i] = m[c - i][b];
            m[c - i][b] = m[c][d - i];
            m[c][d - i] = m[a + i][d];
            m[a + i][d] = tmp;
        }
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i != matrix.length; i++) {
            for (int j = 0; j != matrix[0].length; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }

    /**
     * 回形打印
     *
     * @param matrix
     */
    public static void cyclePrint(int[][] matrix) {
        int a = 0;
        int b = 0;

        int c = matrix.length - 1;
        int d = matrix[0].length - 1;

        while (a <= c && b <= d) {
            cyclePrint(matrix, a++, b++, c--, d--);
        }
    }

    /**
     * 回形打印
     *
     * @param m
     * @param a
     * @param b
     * @param c
     * @param d
     */
    private static void cyclePrint(int[][] m, int a, int b, int c, int d) {
        if (a == c) {
            System.out.print(m[a][b] + "\t");
            return;
        }

        // 打印上边
        for (int i = b; i < d; i++) {
            System.out.print(m[a][i] + "\t");
        }

        // 打印右边
        for (int i = a; i < c; i++) {
            System.out.print(m[i][d] + "\t");
        }

        // 打印下边
        for (int i = d; i > a; i--) {
            System.out.print(m[c][i] + "\t");
        }
        // 打印左边
        for (int i = c; i > a; i--) {
            System.out.print(m[i][b] + "\t");
        }
    }


    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16},
        };
        printMatrix(matrix);
        System.out.println("==============");
        cyclePrint(matrix);
        System.out.println();


        /* rotate(matrix);
        System.out.println("==============");
        printMatrix(matrix);

        System.out.println("==============");
        cyclePrint(matrix);*/

    }
}
